package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVo;
import com.atguigu.gulimall.ware.vo.PurchaseMergeVo;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;
    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryUnreceivedListPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().in("status", Arrays.asList(WareConstant.PurchaseStatusEnum.CREATED.getCode(), WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()))
        );

        return new PageUtils(page);
    }

    @Override
    public void merge(PurchaseMergeVo mergeVo) {
        if (CollectionUtils.isEmpty(mergeVo.getItems())) {
            return;
        }
        List<Long> filterIds = this.listByIds(mergeVo.getItems()).stream().filter(item -> WareConstant.PurchaseStatusEnum.ASSIGNED.getCode().equals(item.getStatus()) || WareConstant.PurchaseStatusEnum.CREATED.getCode().equals(item.getStatus())).map(PurchaseEntity::getId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(filterIds)) {
            return;
        }
        mergeVo.setItems(filterIds);
        Long purchaseId = mergeVo.getPurchaseId();
        if (mergeVo.getPurchaseId() == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity().initDate();
            purchaseEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> purchaseDetailList = mergeVo.getItems().stream().map(item -> new PurchaseDetailEntity(item, finalPurchaseId, WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode())).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(purchaseDetailList);
        if (mergeVo.getPurchaseId() != null) {
            this.updateById(new PurchaseEntity(purchaseId, new Date()));
        }
    }

    @Override
    public void received(List<Long> purchaseIds) {
        this.update(new PurchaseEntity(WareConstant.PurchaseStatusEnum.RECEIVED.getCode()), new UpdateWrapper<PurchaseEntity>().in("id", purchaseIds));
        this.purchaseDetailService.update(new PurchaseDetailEntity(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode()), new UpdateWrapper<PurchaseDetailEntity>().in("purchase_id", purchaseIds));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void done(PurchaseDoneVo purchaseDoneVo) {
        AtomicBoolean isPurchaseSuccess = new AtomicBoolean(true);
        List<PurchaseDetailEntity> failedPurchaseDetailList = new ArrayList<>();
        List<Long> successPurchaseDetailIds = new ArrayList<>();
        purchaseDoneVo.getItems().forEach(item -> {
            if (item.getStatus().equals(WareConstant.PurchaseStatusEnum.ERROR.getCode())) {
                isPurchaseSuccess.set(false);
                failedPurchaseDetailList.add(new PurchaseDetailEntity(item.getItemId(), WareConstant.PurchaseDetailStatusEnum.FAIL.getCode(), item.getReason()));
            }else{
                successPurchaseDetailIds.add(item.getItemId());
            }
        });
        this.updateById(new PurchaseEntity(purchaseDoneVo.getId(), BooleanUtils.isNotTrue(isPurchaseSuccess.get()) ? WareConstant.PurchaseStatusEnum.ERROR.getCode() : WareConstant.PurchaseStatusEnum.FINISHED.getCode()));
        if (CollectionUtils.isNotEmpty(failedPurchaseDetailList)) {
            purchaseDetailService.updateBatchById(failedPurchaseDetailList);
        }
        if (CollectionUtils.isNotEmpty(successPurchaseDetailIds)) {
            purchaseDetailService.update(new PurchaseDetailEntity(WareConstant.PurchaseDetailStatusEnum.FINISHED.getCode()), new UpdateWrapper<PurchaseDetailEntity>().in("id", successPurchaseDetailIds));
            wareSkuService.addStock(successPurchaseDetailIds);
        }
    }

}
